package com.rocksdata.mc.http;

import android.text.TextUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.xutils.common.util.KeyValue;
import org.xutils.http.body.MultipartBody;
import org.xutils.x;
import org.xutils.common.Callback.Cancelable;
import org.xutils.common.Callback.CommonCallback;
import org.xutils.http.HttpMethod;
import org.xutils.http.RequestParams;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.ctz.commonframe.utils.Logger;
import com.rocksdata.mc.business.UserInfoManager;
import com.rocksdata.mc.entity.ImageFileBean;

public class HttpClient {
	private static final String TAG = "HttpClient";

	private static final int RESPONSE_SUCCESS_POST = 201;
	private static final int RESPONSE_SUCCESS_GET = 200;

	public interface OnHttpResultListener<T> {
		void onResult(boolean isSuccess, List<T> data, String msg);
	}

	public interface OnAuthErrorListener {
	    void onAuthError(String msg);
    }

    public static OnAuthErrorListener onAuthErrorListener;

    public static void setOnAuthErrorListener (OnAuthErrorListener listener) {
        onAuthErrorListener = listener;
    }

    public static Cancelable post(String url, Map<String, String> paramsMap, final OnHttpResultListener<Object> listener ) {
        return post(url, paramsMap, null, listener);
    }

    public static Cancelable postWithFile(String url, Map<String, String> paramsMap, String fileKey, File file, final Class clazz, final OnHttpResultListener<Object> listener ) {
        if (file == null || TextUtils.isEmpty(fileKey))
            return post(url, paramsMap, clazz, listener);

        final RequestParams params = buildPostWithFileParams(url, paramsMap, fileKey, file);
        return x.http().post(params, new CommonCallback<ResponseEntity>() {

            @Override
            public void onCancelled(CancelledException arg0) {

            }

            @Override
            public void onError(Throwable arg0, boolean arg1) {
                Logger.e(TAG, "【http post onError】" + params.getUri() + " ,errMsg:" + arg0.getLocalizedMessage());
                if("Unauthorized".equals(arg0.getLocalizedMessage()) || arg0.toString().contains("Unauthenticated")){
                    if (onAuthErrorListener != null) {
                        onAuthErrorListener.onAuthError("账号在其他设备登录，请重新登录");
                        return;
                    }
                }
                listener.onResult(false, null, "访问服务器失败");
            }

            @Override
            public void onFinished() {

            }

            @Override
            public void onSuccess(ResponseEntity arg0) {
                Logger.e(TAG, "【http post onSuccess】" + params.getUri());
                parseResult(HttpMethod.POST, arg0, clazz, listener);
            }
        });
    }

	public static <T> Cancelable post(String url, Map<String, String> paramsMap, final Class<T> clazz, final OnHttpResultListener<T> listener ) {
		final RequestParams params = buildPostParams(url, paramsMap);
		return x.http().post(params, new CommonCallback<ResponseEntity>() {

			@Override
			public void onCancelled(CancelledException arg0) {

			}

			@Override
			public void onError(Throwable arg0, boolean arg1) {
				Logger.e(TAG, "【http post onError】" + params.getUri() + " ,errMsg:" + arg0.getLocalizedMessage());
                if("Unauthorized".equals(arg0.getLocalizedMessage()) || arg0.toString().contains("Unauthenticated")){
				    if (onAuthErrorListener != null) {
				        onAuthErrorListener.onAuthError("账号在其他设备登录，请重新登录");
				        return;
                    }
                }
				listener.onResult(false, null, "访问服务器失败");
			}

			@Override
			public void onFinished() {

			}

			@Override
			public void onSuccess(ResponseEntity arg0) {
				Logger.e(TAG, "【http post onSuccess】" + params.getUri());
				parseResult(HttpMethod.POST, arg0, clazz, listener);
			}
		});
	}

	public static <T> Cancelable get(String url, Map<String, Object> map, final Class<T> clazz, final OnHttpResultListener<T> listener ) {
		final RequestParams params = buildGetParams(url, map);
		return x.http().get(params, new CommonCallback<ResponseEntity>() {

			@Override
			public void onCancelled(CancelledException arg0) {

			}

			@Override
			public void onError(Throwable arg0, boolean arg1) {
				Logger.e(TAG, "【http get onError】" + params.getUri() + " ,msg:"+ arg0.getMessage() + " ,arg0:" + arg0.toString());
                if("Unauthorized".equals(arg0.getLocalizedMessage()) || arg0.toString().contains("Unauthenticated")){
                    if (onAuthErrorListener != null) {
                        onAuthErrorListener.onAuthError("账号在其他设备登录，请重新登录");
                        return;
                    }
                }
                listener.onResult(false, null, "访问服务器失败");
			}

			@Override
			public void onFinished() {

			}

			@Override
			public void onSuccess(ResponseEntity arg0) {
                Logger.e(TAG, "【http get onSuccess】" + params.getUri());
				parseResult(HttpMethod.GET, arg0, clazz, listener);
			}
		});
	}

    private static RequestParams buildPostWithFileParams(String url, Map<String, String> map, String fileKey, File file) {
        RequestParams params = new RequestParams(url);
        params.addHeader("Authorization", "Bearer " + UserInfoManager.getAccessToken());
        if(map != null) {
            for (String key : map.keySet()) {
                params.addBodyParameter(key, map.get(key));
                Logger.e(TAG, "【http post param】" + key + "=" + String.valueOf(map.get(key)));
            }
        }
        params.setMultipart(true);
        params.addBodyParameter(fileKey, file);
        return params;
    }

	private static RequestParams buildPostParams(String url, Map<String, String> map) {
		RequestParams params = new RequestParams(url);
		params.addHeader("Authorization", "Bearer " + UserInfoManager.getAccessToken());
		if(map != null) {
			for (String key : map.keySet()) {
				params.addBodyParameter(key, map.get(key));
				Logger.e(TAG, "【http post param】" + key + "=" + String.valueOf(map.get(key)));
			}
		}
		return params;
	}

	private static RequestParams buildGetParams(String url, Map<String, Object> map) {
		RequestParams params = new RequestParams(url);
		params.addHeader("Authorization", "Bearer " + UserInfoManager.getAccessToken());
        if(map != null) {
            for (String key : map.keySet()) {
                params.addBodyParameter(key, String.valueOf(map.get(key)));
                Logger.e(TAG, "【http get param】" + key + "=" + String.valueOf(map.get(key)));
            }
        }
		return params;
	}

	private static <T> void parseResult(HttpMethod method, ResponseEntity entity, Class<T> clazz, final OnHttpResultListener<T> listener) {
		if(RESPONSE_SUCCESS_POST == entity.errorCode
				|| RESPONSE_SUCCESS_GET == entity.errorCode) {
//			Logger.e(TAG, "【business success】");
			if (clazz == null) {
				listener.onResult(true, null, entity.errorMsg);
			} else {
				if (entity.data != null) {
					Logger.e(TAG, "response data:" + entity.data);
					List<T> dataList = new ArrayList<>();
					if (entity.data.startsWith("[")) {
						List<T> list = JSONArray.parseArray(entity.data, clazz);
						dataList.addAll(list);
					} else if (entity.data.startsWith("{")) {
						T t = JSON.parseObject(entity.data, clazz);
						dataList.add(t);
					}
					listener.onResult(true, dataList, entity.errorMsg);
				} else {
					listener.onResult(true, null, entity.errorMsg);
				}
			}
//		}else if(){

		}else{
			Logger.e(TAG, "【http response error】" + entity.errorMsg);
            if(listener != null)
			    listener.onResult(false, null, entity.errorMsg);
		}
	}

	public static Cancelable upload(int businessType, String url, String filePath, final OnHttpResultListener<ImageFileBean> listener){
//		Logger.e(TAG, "上传文件，url=" + url + ",type=" + businessType + ",path=" + filePath);
        RequestParams params = new RequestParams(url);
        params.setAsJsonContent(true);
        List<KeyValue> list = new ArrayList<>();
        list.add(new KeyValue("imagefile", new File(filePath)));
        list.add(new KeyValue("type", businessType));
        MultipartBody body = new MultipartBody(list, "UTF-8");
        params.setRequestBody(body);
        return x.http().post(params, new CommonCallback<ResponseEntity>() {
            @Override
            public void onSuccess(ResponseEntity entity) {
//                Logger.e(TAG, "【http upload onSuccess】" + entity.data);
                if(RESPONSE_SUCCESS_POST == entity.errorCode){
//                    Logger.e(TAG, "【business success】");
                    ImageFileBean bean = JSON.parseObject(entity.data, ImageFileBean.class);
                    List<ImageFileBean> list = new ArrayList<ImageFileBean>();
                    list.add(bean);
                    if(listener != null)
                        listener.onResult(true, list, entity.errorMsg);
                }else{
//                    Logger.e(TAG, "【http response fail】" + entity.errorMsg);
                    if(listener != null)
                        listener.onResult(false, null, entity.errorMsg);
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
//                Logger.e(TAG, "【http upload onError】" + ex.getLocalizedMessage());
                listener.onResult(false, null, ex.getLocalizedMessage());
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
	}
}
